﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Bravura.Editing.Common.Controls
{
	public class SelectionGrid : Grid
	{
		#region Fields

		private bool _selecting;
		private Point _downPoint;
		private Point _lastPoint;
		private Rectangle _selectionRect;
		private ISelectionClient _client;

		#endregion

		public SelectionGrid()
		{
			this.Background = Brushes.Transparent;

			_selectionRect = new Rectangle();
			_selectionRect.Fill = new SolidColorBrush(Color.FromArgb(20, 0, 0, 255));
			_selectionRect.Stroke = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0));
			_selectionRect.HorizontalAlignment = HorizontalAlignment.Left;
			_selectionRect.VerticalAlignment = VerticalAlignment.Top;
			_selectionRect.RadiusX = 1.5;
			_selectionRect.RadiusY = 1.5;
			this.Children.Add(_selectionRect);

			SetZIndex(_selectionRect, 8000);
		}

		public void SetClient(ISelectionClient client)
		{
			_client = client;
		}

		#region Overrides

		protected override void OnMouseDown(MouseButtonEventArgs e)
		{
			_selecting = true;
			_downPoint = e.GetPosition(this);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			if (_selecting)
			{
				_lastPoint = e.GetPosition(this);
				Thickness margin = _selectionRect.Margin;
				margin.Left = Math.Min(_downPoint.X, _lastPoint.X);
				margin.Top = Math.Min(_downPoint.Y, _lastPoint.Y);
				_selectionRect.Margin = margin;
				_selectionRect.Width = Math.Abs(_lastPoint.X - _downPoint.X);
				_selectionRect.Height = Math.Abs(_lastPoint.Y - _downPoint.Y);
				if (_client != null)
				{
					_client.Selecting(_downPoint, _lastPoint);
				}
			}
		}

		protected override void OnMouseUp(MouseButtonEventArgs e)
		{
			_selecting = false;
			_lastPoint = e.GetPosition(this);
			_selectionRect.Width = 0;
			_selectionRect.Height = 0;
			if (_client != null)
			{
				_client.SelectionMade(_downPoint, _lastPoint);
			}
		}

		#endregion
	}

	public interface ISelectionClient
	{
		void Selecting(Point downPoint, Point lastPoint);
		void SelectionMade(Point downPoint, Point lastPoint);
	}
}
